﻿using JWT;
using JWT.Algorithms;
using JWT.Serializers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace SignalRTest
{
    public class JWTHelper
    {
        private static string secret = "GQDstcKsx0NHjPOuXOYg5MbeJ1XT0uFiwDVvVBrk!@#$%";

        public static string Encrypt(string userName)
        {
            var payload = new Dictionary<string, object>
            {
                { "userName", userName }
            };

            IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
            IJsonSerializer serializer = new JsonNetSerializer();
            IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
            IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);

            var token = encoder.Encode(payload, secret);
            return token;
        }

        public static string Decrypt(string token)
        {
            try
            {
                IJsonSerializer serializer = new JsonNetSerializer();
                IDateTimeProvider provider = new UtcDateTimeProvider();
                IJwtValidator validator = new JwtValidator(serializer, provider);
                IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
                IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder);

                var json = decoder.DecodeToObject<Dictionary<string,string>>(token, secret, verify: true);
                return json["userName"];
                //Console.WriteLine(json);
            }
            catch (TokenExpiredException)
            {
                return null;
               // Console.WriteLine("Token has expired");
            }
            catch (SignatureVerificationException)
            {
                return null; 
                //Console.WriteLine("Token has invalid signature");
            }
        }
     }
}